package class03_一些基础的数据结构.test;

import java.util.Stack;

public class Code05_GetMinStack {
    public static class myStack{
        private Stack<Integer> stackData;
        private Stack<Integer> stackMin;
        public myStack(){
            stackData = new Stack<>();
            stackMin = new Stack<>();
        }
        public void push(int val){
            if(this.stackMin.isEmpty()){
                this.stackMin.push(val);
            }else if(this.getMin() > val){
                this.stackMin.push(val);
            }
            this.stackData.push(val);
        }
        public int pop(){
            if(this.stackData.isEmpty()){
                throw new RuntimeException("Your stack is empty.");
            }
            Integer pop = this.stackData.pop();
            if(pop == this.getMin()){
                this.stackMin.pop();
            }
            return pop;
        }
        public int getMin(){
            if(this.stackMin.isEmpty()){
                throw new RuntimeException("Your stack is empty.");
            }
            return this.stackMin.peek();
        }
    }
    public static class myStack2{
        private Stack<Integer> stackData;
        private Stack<Integer> stackMin;
        public myStack2(){
            stackData = new Stack<>();
            stackMin = new Stack<>();
        }
        public void push(int val){
            if(this.stackMin.isEmpty()){
                this.stackMin.push(val);
            }else if(this.getMin() > val){
                this.stackMin.push(val);
            }else {
                this.stackMin.push(getMin());
            }
            this.stackData.push(val);
        }
        public int pop(){
            if(this.stackData.isEmpty()){
                throw new RuntimeException("stack is empty!");
            }else {
                this.stackMin.pop();
                return this.stackData.pop();
            }
        }
        private int getMin() {
            if(this.stackMin.isEmpty()){
                throw new RuntimeException("stack is empty!");
            }
            return this.stackMin.peek();
        }
    }
    public static void main(String[] args) {
        myStack stack1 = new myStack();
        stack1.push(3);
        System.out.println(stack1.getMin());
        stack1.push(4);
        System.out.println(stack1.getMin());
        stack1.push(1);
        System.out.println(stack1.getMin());
        System.out.println(stack1.pop());
        System.out.println(stack1.getMin());

        System.out.println("=============");

        myStack2 stack2 = new myStack2();
        stack2.push(3);
        System.out.println(stack2.getMin());
        stack2.push(4);
        System.out.println(stack2.getMin());
        stack2.push(1);
        System.out.println(stack2.getMin());
        System.out.println(stack2.pop());
        System.out.println(stack2.getMin());
    }
}
